package com._5704.website.controller;

import com._5704.website.exception.WebsiteException;
import com._5704.website.exception.WebsiteExceptionEnum;
import com._5704.website.util.JsonUtil;
import com._5704.website.vo.JsonVO;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.ShiroException;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@ControllerAdvice
@ResponseBody
@Log4j2
public class ExceptionController {

    /**
     * 捕获异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonVO catchError(ConstraintViolationException e){
        StringBuffer str = new StringBuffer();

        e.getConstraintViolations().forEach(violation -> str.append(violation.getMessage()).append("。"));

        JsonVO<String> jsonVO = JsonUtil.error(WebsiteExceptionEnum.DATA_ERROR, str.toString());

        e.printStackTrace();

        return jsonVO;
    }

    /**
     * 捕获异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(WebsiteException.class)
    public JsonVO catchError(WebsiteException e){
        JsonVO<String> jsonVO = JsonUtil.error(e.getWebsiteExceptionEnum(), e.getMessage());
        e.printStackTrace();
        return jsonVO;
    }

    /**
     * 捕获异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(ShiroException.class)
    public JsonVO catchError(ShiroException e){
        JsonVO<String> jsonVO = JsonUtil.error(WebsiteExceptionEnum.Insufficient_Permissions, e.getMessage());
        e.printStackTrace();
        return jsonVO;
    }


    /**
     * 捕获异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(FileUploadException.class)
    public JsonVO catchError(FileUploadException e){
        JsonVO<String> jsonVO = JsonUtil.error(WebsiteExceptionEnum.DATA_ERROR, e.getMessage());
        e.printStackTrace();
        return jsonVO;
    }
    /**
     * 捕获异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public JsonVO catchError(FileSizeLimitExceededException e){
        JsonVO<String> jsonVO = JsonUtil.error(WebsiteExceptionEnum.PICTURE_LIMIT_MAX_SIZE, e.getMessage());
        e.printStackTrace();
        return jsonVO;
    }
}

